<?php
/**
 * helps.php
 *
 * 助手类文件
 */

/**
 * 模板初始化
 * * @param mixed $tpl 
 * @param mixed $args 
 * @access public
 * @return void
 */
function template($tpl, $args = NULL)
{
	global $_SGLOBAL, $config;
	if(!isset($_SGLOBAL['view']) || !$_SGLOBAL['view'])
	{
		include_once $config['libs'] . './smarty/Smarty.class.php';
		$_SGLOBAL['view'] = new Smarty;

		foreach($config['view'] as $k => $v)
		{
			$_SGLOBAL['view']->$k = $v;
		}
	}

	isset($_SGLOBAL['assign']) && count($_SGLOBAL['assign'])>0 ? $_SGLOBAL['view']->assign($_SGLOBAL['assign']) : '';
	isset($args[1]) ? $_SGLOBAL['view']->assign($args[1]) : '';
	include_once $config['config'] . './titleConfig.php';
	$sTpl = substr($tpl,0,-4);
	if(!empty($titleConfig)){
	if(array_key_exists($sTpl,$titleConfig))
		$_SGLOBAL['view']->assign('topTitle', (isset($args[1]['topTitle'])  ? $args[1]['topTitle'] . '-' : '') . $titleConfig[$sTpl]);
}
	if($sTpl == 'min_game/list' && isset($args[1]['topTitle']))
		$_SGLOBAL['view']->assign('topTitle', $args[1]['topTitle'] . '-' . $titleConfig['min_game/index']);

	if(!isset($args[0]) || !$args[0])
		$args[0] = 'display';

	return $_SGLOBAL['view']->$args[0]($tpl);
}

/**
 * 添加过滤转义
 * 
 * @param mixed $string 
 * @access public
 * @return void
 */
function saddslashes($string)
{
	if(is_array($string))
	{
		foreach($string as $key => $val)
		{
			$string[$key] = saddslashes($val);
		}
	}
	else
		$string = addslashes($string);

	return $string;
}

/**
 * 去掉slassh 
 * 
 * @param mixed $string 
 * @access public
 * @return void
 */
function sstripslashes($string)
{
	if(is_array($string))
	{
		foreach($string as $key => $val)
		{
			$string[$key] = sstripslashes($val);
		}
	}
	else
		$string = stripslashes($string);

	return $string;
}

/**
 * 查找字符串
 * 
 * @param mixed $haystack 
 * @param mixed $needle 
 * @access public
 * @return void
 */
function strExists($haystack, $needle)
{
	return !(strpos($haystack, $needle) === FALSE);
}

/**
 * 取消HTML代码
 * 
 * @param mixed $string 
 * @access public
 * @return void
 */
function shtmlspecialchars($string)
{
	if(is_array($string))
	{
		foreach($string as $key => $val)
		{
			$string[$key] = shtmlspecialchars($val);
		}
	}
	else
	{
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
		str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}

/**
 * 验证用户是否登录 
 * 
 * @access public
 * @return void
 */
function checkAuth()
{
	global $_SCOOKIE, $_SGLOBAL, $config, $cache, $assign;

	if(isset($_SCOOKIE['auth']) && $_SCOOKIE['auth'])
	{
		list($password, $uid) = explode("\t", authCode($_SCOOKIE['auth'], 'DECODE'));
		$_SGLOBAL['supeUid'] = intval($uid);

		if($password && $_SGLOBAL['supeUid'])
		{
			$user = getOnlineInfo($_SGLOBAL['supeUid']);

			// 明星帐号同时登录($_SGLOBAL['supeUid'] <= 100008)
			if(($user['password'] == $password || $_SGLOBAL['supeUid'] <= 100008) && $_SGLOBAL['timestamp']-$user['lastTime'] <= $config['keepAlive'])
			{
				//更新cookie
				ssetcookie('auth', $_SCOOKIE['auth'], $config['keepAlive']);

				$_SGLOBAL['supeUsername'] = addslashes($user['userName']);
				$_SGLOBAL['session'] = $user;

				require_once $config['modules'] . './UserInfo.php';
				$uInfo = new UserInfo;
				$userInfoArr = array('uName' => $_SGLOBAL['supeUsername'], 'uId' => $_SGLOBAL['supeUid']);
				$uBase = $uInfo->getUserBase($userInfoArr);
				$_SGLOBAL['supeTruename'] = $uBase['ub_truename'];

				$uHonor = $uInfo->getUserHonor($userInfoArr);
				$_SGLOBAL['supeSex'] = $uInfo->getUserSex($_SGLOBAL['supeUid'], $_SGLOBAL['supeUsername']);
				$_SGLOBAL['supeAvatar'] = str_replace($config['cdnUrl'], '' ,getImage($uHonor['ul_avatar'], 1, $_SGLOBAL['supeSex']));
				$_SGLOBAL['supeGold'] = $uInfo->getGolds($_SGLOBAL['supeUid']);
				$_SGLOBAL['supeZcoin'] = $uInfo->getZcoins($_SGLOBAL['supeUid']);
				$_SGLOBAL['supeAvatarData'] =  $uHonor['ul_avatar'];
				$_SGLOBAL['supePic'] = $uHonor['uh_pic'];

				if ($_SGLOBAL['timestamp'] - $user['lastTime'] > 300)
                {
					//更新lastTime
					$user['lastTime'] = $_SGLOBAL['timestamp'];
					updateOnlineInfo($user);
                }

				//设置vip标志
				$_SGLOBAL['supeVip'] = $uInfo->userIsVip($userInfoArr['uId']);

				//模板调用
				$_SGLOBAL['assign']['loginUid'] = $_SGLOBAL['supeUid'];
				$_SGLOBAL['assign']['loginUsername'] = $_SGLOBAL['supeUsername'];
				$_SGLOBAL['assign']['loginTruename'] = $_SGLOBAL['supeTruename'];
				$_SGLOBAL['assign']['loginGold'] = $_SGLOBAL['supeGold'] ? $_SGLOBAL['supeGold'] : 0;
				$_SGLOBAL['assign']['loginZcoin'] = $_SGLOBAL['supeZcoin'] ? $_SGLOBAL['supeZcoin'] : 0;
				$_SGLOBAL['assign']['loginAvatar'] = $_SGLOBAL['supeAvatar'];
				$_SGLOBAL['assign']['otherSchool'] = getMySchool($_SGLOBAL['supeUid']);
			}
			else
				$_SGLOBAL['supeUid'] = 0;
		}
		else
			$_SGLOBAL['supeUid'] = 0;
	}

	if(empty($_SGLOBAL['supeUid']))
		clearcookie();
	else
		$_SGLOBAL['supeUsername'] = $user['userName'];
}

/**
 * 更新用户在线信息
 * 
 * @param mixed $uId 
 * @param mixed $uName 
 * @param mixed $uTrueName 
 * @param mixed $user 
 * @access public
 * @return void
 */
function updateOnlineInfo($user)
{
	global $_SGLOBAL, $config, $cache;

	//创建登录的session到缓存中，并缓存用户信息
	require_once $config['libs'] . './dal/Dal.php';
	$dal = new Dal();
	$tCache = $dal->initCache($cache['tempCache'], $cache['tempCacheType']);
	if($tCache->set('user:auth:' . $_SGLOBAL['supeUid'], $user, $config['keepAlive']) === false)
	{
		global $db;
		require_once $config['libs'] . './DaChoose.php';
		$dc = new DaChoose($db);
		$dbObj = $dal->initDb($dc->setModule('common')->setAction('w')->getConfig());
		$dbObj->query('UPDATE ppl_online_users SET ou_lasttime = "' . $_SGLOBAL['timestamp'] . '" WHERE ub_id = "' . $_SGLOBAL['supeUid'] . '"');
	}
	else
	{
		$permCache = $dal->initCache($cache['permCache'], $cache['permCacheType']);
		//将用户id写入排行队列
		$permCache->rpush('user:online:list', json_encode(array($_SGLOBAL['supeUid'], 'UPDATE ppl_online_users SET ou_lasttime = "' . $_SGLOBAL['timestamp'] . '" WHERE ub_id = "' . $_SGLOBAL['supeUid'] . '"')));
	}
}

/**
 * 清空cookie
 * 
 * @access public
 * @return void
 */
function clearcookie()
{
	global $_SGLOBAL, $config, $cache;
	ssetcookie('auth', '', -86400 * 365);
	setcookie($config['cookiePre'].'auth', '', -86400*365, '/', 'www.ppl419.com', 0);

	$_SGLOBAL['supeUid'] = 0;
	$_SGLOBAL['supeUsername'] = '';
}

/**
 * 判断提交是否正确
 * 
 * @param mixed $var 
 * @access public
 * @return void
 */
function submitCheck($var)
{
	if(!empty($_POST[$var]) && $_SERVER['REQUEST_METHOD'] == 'POST')
	{
		if((empty($_SERVER['HTTP_REFERER']) || preg_replace("/https?:\/\/[img|www]*[.]*([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/[img|www]*[.]*([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])) && $_POST['formhash'] == formHash())
			return true;
		else
			showMessage('非法提交','',1,1);
		return true;
	}
	else
		return false;
}

/**
 * 产生form防伪码
 * 
 * @access public
 * @return void
 */
function formHash()
{
	global $_SGLOBAL, $config;
	if(empty($_SGLOBAL['formhash']))
		$_SGLOBAL['formhash'] = substr(md5(substr($_SGLOBAL['timestamp'], 0, -7).'|'.$_SGLOBAL['supeUid'].'|'.md5($config['pplKey'])), 8, 8);

	return $_SGLOBAL['formhash'];
}

/**
 * 验证验证码 
 * 
 * @param mixed $code 
 * @access public
 * @return void
 */
function checkSecCode($code)
{
	global $config;
	require_once $config['libs'] . './seccode/SecCode.php';
	return SecCode::check($code);
}

/**
 * 设置对话框 
 * 
 * @param mixed $message 
 * @param string $urlForward 
 * @param int $second 
 * @param int $inajaxErr 
 * @access public
 * @return void
 */
function showMessage($message, $urlForward = '', $second = 1, $inajaxErr = 0)
{
    global $config, $_SCONFIG, $_SGLOBAL;
    //显示
	if(empty($_SGLOBAL['inajax']) && $urlForward && empty($second) && empty($_SGLOBAL['isflash']))
	{
		header("HTTP/1.1 301 Moved Permanently");
		header("Location: $urlForward");
	}
	else
	{
		if($_SGLOBAL['inajax'])
		{
			$rMsg = array('msg' => $message);
			$inajaxErr == 1 ? $rMsg['err'] = 1 : '';
			if($urlForward)
				$rMsg['forward'] = $urlForward;

			echo json_encode($rMsg);
		}
		elseif($_SGLOBAL['isflash'])
		{
			echo 9999;
			exit();
		}
		else
            template('modules/showmessage.tpl', array('display', array('message' => $message, 'urlForward' => $urlForward, 'second' => $second*1000, 'uId' => $_SGLOBAL['supeUid'])));
	}
	exit();
}

/**
 * cookie设置
 * 
 * @param mixed $var 
 * @param mixed $value 
 * @param int $life 
 * @access public
 * @return void
 */
function ssetcookie($var, $value, $life=0)
{
	global $_SGLOBAL, $_SERVER, $config;
	setcookie($config['cookiePre'].$var, $value, $life ? ($_SGLOBAL['timestamp'] + $life) : 0,  
			$config['cookiePath'], $config['cookieDomain'], $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}

/**
 * 判断邮箱
 * 
 * @param mixed $email 
 * @access public
 * @return void
 */
function checkEmail($email) 
{
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

/**
 * 获取道具图标文件名 
 * 
 * @param mixed $id 
 * @param mixed $ext 
 * @access public
 * @return void
 */
function getImageName($id, $ext = 'png')
{
	return $ext ? substr(md5($id), 8, 16) . '.' . $ext : substr(md5($id), 8, 16);
}

/**
 * 获取avatar图片路径
 * 
 * @param mixed $avatar 
 * @param mixed $avatarRoot 
 * @param mixed $ext 
 * @access public
 * @return void
 */
function getAvatarImageDir($avatar, $avatarRoot = NULL, $ext = NULL)
{
	$md = getImageName($avatar, '');
	$r = $avatarRoot . substr($md, 0, 2) . DIRECTORY_SEPARATOR . substr($md, 2, 2) . DIRECTORY_SEPARATOR . substr($md, 4, 2) . DIRECTORY_SEPARATOR;
	$ext ? $r .= $md . '.' . $ext : '';
	return $r;
}

/**
 * 创建avatar图片路径 
 * 
 * @param mixed $avatar 
 * @access public
 * @return void
 */
function mkAvatarImageDir($avatar, $avatarRoot)
{
	$str = getImageName($avatar, '');
	$dir = $avatarRoot;
	$i = 0;
	while($i<5)
	{
        $dir .= substr($str,$i,2) . DIRECTORY_SEPARATOR;
		if(!is_dir($dir)) mkdir($dir);
		$i = $i + 2;
	}

	return $dir;
}

/**
 * 字符串解密加密
 * 
 * @param mixed $string 
 * @param string $operation 
 * @param string $key 
 * @param int $expiry 
 * @access public
 * @return void
 */
function authCode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
	global $config;
	$ckey_length = 4;	// 随机密钥长度 取值 0-32;
				// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
				// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
				// 当此值为 0 时，则不产生随机密钥

	$key = md5($key ? $key : $config['pplKey']);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++)
	{
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++)
	{
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++)
	{
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE')
	{
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
			return substr($result, 26);
		else
			return '';
	}
	else
		return $keyc.str_replace('=', '', base64_encode($result));
}
/**
 * 过滤字符串 
 * 
 * @param mixed $string 
 * @param mixed $length 
 * @param int $in_slashes 
 * @param int $out_slashes 
 * @param int $html 
 * @access public
 * @return void
 */
function getStr($string, $length, $inSlashes = 0, $outSlashes = 0, $html = 0, $isDiff = 0) 
{
	global $_SGLOBAL;
	$string = trim($string);
	if($inSlashes)
		//传入的字符有slashes
		$string = sstripslashes($string);

	if($html < 0)
	{
		//去掉html标签
		$string = preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $string);
		$string = shtmlspecialchars($string);
	}
	elseif($html == 0)
		//转换html标签
		$string = shtmlspecialchars($string);

	if($length)
	{
		$string = $isDiff ? mb_substr($string, 0, $length, 'UTF-8') : leftLen($string, $length);
	}

	if($outSlashes)
		$string = saddslashes($string);

	return trim($string);
}
/**
 * 取得客户端的ip 
 * 
 * @access public
 * @return void
 */
function getClientIp()
{
	if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'])
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	else
	{
		if(isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'])
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		else
			$ip = $_SERVER['REMOTE_ADDR'];
	}

	return $ip;
}

/**
 * 用户头像
 * 
 * @param mixed $uId 
 * @access public
 * @return void
 *
function getUserPic($uId)
{
	global $config;
	$picFile = getAvatarImageDir($uId,'','jpg');
	if(file_exists($config['pictureDir'] . $picFile)) return 'attachment/pic/' . $picFile;
	return 'image/default_pic.gif';
}
*/
/**
 * 获取avatar图片
 * 
 * @param mixed $avatar 
 * @param int $sex 
 * @access public
 * @return void
 *
function getUserAvatar($avatar, $sex = 1)
{
	global $config;
	$imgUrl = getAvatarImageDir($avatar,'','png');
	if(file_exists($config['avatarDir'] . $imgUrl)) return 'attachment/avatar/' . $imgUrl;
	return $sex == 1 ? 'image/default_boy_avatar.png' : 'image/default_gril_avatar.png';
}
*/
/**
 * 根据年月推算天数
 * 
 * @param mixed $year 
 * @param mixed $month 
 * @access public
 * @return void
 */
function getDay($year, $month)
{
	$day = 31;
	if($month == 2)
	{
		if($year % 400 == 0 || $year % 4 == 0 && $year % 100 != 0)  $day = 29;
		else $day = 28;
	}
	elseif($month < 8)
		$day = ($month % 2 == 1) ? 31 : 30;
	else 
		$day = ($month % 2 == 1) ? 30 : 31;
	return $day;
}

/**
 * 跳转 
 * 
 * @param string $url 
 * @access public
 * @return void
 */
function redirect($url)
{
	global $_SGLOBAL;
	if($_SGLOBAL['inajax'])
	{
		$rMsg['err'] = 1;
		$rMsg['forward'] = $url;
		echo json_encode($rMsg);
	}
	else
	{
		header("HTTP/1.1 301 Moved Permanently");
		header("Location: $url");
	}
	exit;
}
/**
 * 处理积分星星
 * 
 * @param mixed $experience 
 * @access public
 * @return void
 */
function getStar($experience) 
{
	global $config;

	$starimg = '';
	if($config['starCredit'] > 1) 
	{
		//计算星星数
		$starnum = intval($experience/$config['starCredit']); //+1;
		if($config['starLevelNum'] < 2) 
		{
			if($starnum > 16) $starnum = 16;
			for($i = 0; $i < $starnum; $i++) 
			{
				$starimg .= '<img src="' . $config['cdnUrl'] . 'image/img/star/star_level16.png" align="absmiddle" />';
			}
		} 
		else 
		{
			//计算等级(10个)
			for($i = 16; $i > 0; $i--) 
			{
				$numlevel = intval($starnum / pow($config['starLevelNum'], ($i - 1)));
				if($numlevel > 16) $numlevel = 16;
				if($numlevel) 
				{
					for($j = 0; $j < $numlevel; $j++) 
					{
						$starimg .= '<img src="' . $config['cdnUrl'] . 'image/img/star/star_level'.$i.'.png" align="absmiddle" />';
					}
					break;
				}
			}
		}
	}
	//if(empty($starimg)) $starimg = '<img src="' . $config['cdnUrl'] . 'image/credit.gif" alt="'.$experience.'" align="absmiddle" alt="'.$experience.'" title="'.$experience.'" />';
	return $starimg;
}

/**
 * 登录插入临时表 
 * 
 * @param mixed $info 
 * @access public
 * @return void
 */
function setOnlineInfo($uId, $uName, $uTrueName, $uStatus = 0)
{
	global $_SGLOBAL, $config, $cache;
	//创建cookie
	$authPass = md5($uId . $_SGLOBAL['timestamp']);
	$cookieTime = $uStatus ? 31536000 : '';
	ssetcookie('auth', authCode($authPass . "\t" . $uId, 'ENCODE'), $cookieTime);
	ssetcookie('loginuser', $uName, 31536000);

	//创建登录的session到缓存中，并缓存用户信息
	require_once $config['libs'] . './dal/Dal.php';
	$dal = new Dal();
	$tCache = $dal->initCache($cache['tempCache'], $cache['tempCacheType']);
	$authInfo = array('password' => $authPass, 'lastTime' => $_SGLOBAL['timestamp'], 'userName' => $uName);
	$sql = 'REPLACE INTO ppl_online_users(ub_id, ub_name, ub_truename, ou_lasttime, ou_password)
			VALUES("' . $uId . '", "' . $uName . '", "' . $uTrueName . '", "' . $_SGLOBAL['timestamp'] . '", "' . $authPass . '")';
	//将登录信息写入临时表
	$qCache = $dal->initCache($cache['permCache'], $cache['permCacheType']);
	if($tCache->set('user:auth:' . $uId, $authInfo, $config['keepAlive']) === false)
	{
		global $db;
		require_once $config['libs'] . './DaChoose.php';
		$dc = new DaChoose($db);
		$dbObj = $dal->initDb($dc->setModule('common')->setAction('w')->getConfig());
		$dbObj->query($sql);
	}
	else
	{
		$qCache->rpush('user:online:list', json_encode(array($uId, $sql)));
	}

	//将用户id写入排行队列
	$qCache->rpush('RankRequest', $uId);
}

/**
 * 取得在线用户验证信息 
 * 
 * @access public
 * @return void
 */
function getOnlineInfo($uId)
{
	global $config, $db, $cache, $_SGLOBAL;
	$user = array();

	require_once $config['libs'] . './dal/Dal.php';
	require_once $config['libs'] . './DaChoose.php';

	$dal = new Dal();
	$cObj = $dal->initCache($cache['tempCache'], $cache['tempCacheType']);
	if(($user = $cObj->get('user:auth:' . $_SGLOBAL['supeUid'])) === false)
	{
		$dc = new DaChoose($db);
		$dbObj = $dal->initDb($dc->setModule('common')->setAction('r')->getConfig());
		$dbObj->query('SELECT ub_name AS userName, ou_password AS password, ou_lasttime AS lastTime, ub_truename AS userTrueName, ub_id AS userid
						FROM ppl_online_users WHERE ub_id = "' . $uId . '" AND ou_lasttime >= ' . ($_SGLOBAL['timestamp'] - $config['keepAlive']) . ' LIMIT 1');
		if ($user = $dbObj->fetchArray(MYSQLI_ASSOC))
		{
			$cObj = $dal->initCache($cache['tempCache'], $cache['tempCacheType']);
			$cObj->set('user:auth:' . $uId, $user);
		}
	}

	return $user;
}

/**
 * 数组排序
 * 
 * @param mixed $arrayData 
 * @param mixed $keyName1 
 * @param string $sortOrder1 
 * @param string $sortType1 
 * @access public
 * @return void
 */
function sysSortArray($arrayData, $keyName1, $sortOrder1 = 'SORT_ASC', $sortType1 = 'SORT_REGULAR')
{
	if(!is_array($arrayData)) return $arrayData;
	$argCount = func_num_args();
	for($i = 1;$i < $argCount;$i++)
	{
		$arg = func_get_arg($i);
		if(!preg_match("/SORT/",$arg))
		{
			$keyNameList[] = $arg;
			$sortRule[] = '$' . $arg;
		}
		else
		{
			$sortRule[] = $arg;
		}
	}
	foreach($arrayData as $key => $info)
	{
		foreach($keyNameList as $keyName)
		{
			${$keyName}[$key] = $info[$keyName];
		}
	}
	$evalString = 'array_multisort(' . join(",",$sortRule) . ',$arrayData);';
	eval($evalString);
	return $arrayData;
}

/**
 * 徽章图片
 * 
 * @param mixed $badId 
 * @access public
 * @return void
 *
function getBadgeImage($badId)
{
	global $config;
	$imageFile = getAvatarImageDir($badId,'','jpg');
	if(file_exists($config['badgeDir'] . $imageFile)) return 'attachment/badge/' . $imageFile;
	return 'image/default_badge.jpg';
}
*/
/**
 * 截取字符串
 * 
 * @param mixed $str 
 * @param mixed $len 
 * @access public
 * @return void
 */
function leftLen($str, $len)
{
	while(strlen($str) > $len)
	{
		$str = mb_substr($str, 0, mb_strlen($str , 'UTF-8') - 1, 'UTF-8');
	}
	return $str;
}

/**
 * 表情
 * 
 * @param mixed $message 
 * @access public
 * @return void
 */
function bbCode($message) 
{
	global $_SGLOBAL;
	
	if(empty($_SGLOBAL['search_exp'])) 
	{
		$_SGLOBAL['search_exp'] = array(
			"/\s*\[quote\][\n\r]*(.+?)[\n\r]*\[\/quote\]\s*/is",
			"/\[url\]\s*(https?:\/\/|ftp:\/\/|gopher:\/\/|news:\/\/|telnet:\/\/|rtsp:\/\/|mms:\/\/|callto:\/\/|ed2k:\/\/){1}([^\[\"']+?)\s*\[\/url\]/i",
			"/\[em:(.+?):\]/i",
			"/\[url\s*(https?:\/\/|ftp:\/\/|gopher:\/\/|news:\/\/|telnet:\/\/|rtsp:\/\/|mms:\/\/|callto:\/\/|ed2k:\/\/){1}([^\[\]\"']+?)\]([^\s]+)\[\/url\]/i",
			"/\[url[\s\<a]+href=\"([^\"]+)\"[^\]]+\]([^\s]+)\[\/url\]/i",
		);
		$_SGLOBAL['replace_exp'] = array(
			"<div class=\"quote\"><span class=\"q\">\\1</span></div>",
			"<a href=\"\\1\\2\" target=\"_blank\">\\1\\2</a>",
			"<img src=\"image/face/\\1.gif\" class=\"face\">",
			"<a href=\"\\1\\2\" target=\"_blank\">\\3</a>",
			"<a href=\"\\1\" target=\"_blank\">\\2</a>",
		);
		$_SGLOBAL['search_str'] = array('[b]', '[/b]','[i]', '[/i]', '[u]', '[/u]');
		$_SGLOBAL['replace_str'] = array('<b>', '</b>', '<i>','</i>', '<u>', '</u>');
	}
	@$message = str_replace($_SGLOBAL['search_str'], $_SGLOBAL['replace_str'],preg_replace($_SGLOBAL['search_exp'], $_SGLOBAL['replace_exp'], $message));
	return nl2br(str_replace(array("\t", '   ', '  '), array('&nbsp; &nbsp; &nbsp; &nbsp; ', '&nbsp; &nbsp;', '&nbsp;&nbsp;'), $message));
}

/**
 * 返回分页页码 
 * 
 * @param mixed $allPage 
 * @param int $nums 
 * @param int $curPage 
 * @access public
 * @return void
 * @usage splitPage(3, 3, 3);
 */
function splitPage($allNums, $perPage = 50, $nums = 3, $curPage = 1)
{
	if($perPage == 0)
		$allPage = $allNums;
	else
		$allPage = ceil($allNums / $perPage);
	$curPage > $allPage ? $curPage = $allPage : '';
	$endNum = $curPage+$nums;
	$startNum = $curPage-$nums;
	if($endNum > $allPage)
		$endNum = $allPage;

	if($startNum <= 0)
		$startNum = 1;

	$r = $endNum-$startNum+1;
	$o = 2*$nums+1;
	$n = $o-$r;
	if($r < $o)
	{
		if($endNum == $allPage)
		{
			$temp = $startNum-$n;
			if($temp > 0)
				$startNum = $temp;
			else
				$startNum = 1;
		}
		else if($startNum == 1)
		{
			$temp = $endNum+$n;
			if($temp < $allPage)
				$endNum = $temp;
			else
				$endNum = $allPage;
		}
	}

	$nu = array();
	for($i = $startNum; $i <= $endNum; $i++)
	{
		$nu[] = $i;
	}
	$allPage = $allPage > 1 ? $allPage : 1;
	return array('maxPage' =>$allPage, 'pageNums' => $nu, 'curPage' => $curPage);
}

/**
 * 判断用户是否登录 
 * 
 * @access public
 * @return void
 */
function checkLogin($r = false, $re = NULL)
{
	global $_SGLOBAL, $config;
	$refer = '';
	if($r === true)
		$refer = urlencode($config['pplUrl'] . $_SERVER['REQUEST_URI']);
	else if($r === false && $re == 1)
		isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] ? $refer = $_SERVER['HTTP_REFERER'] : '';
	else if($r === false && $re && $re != 1)
		$refer = $re;

	if(!$_SGLOBAL['supeUid'] || !$_SGLOBAL['supeUsername'])
		showMessage('请先登录', 'index.php?refer=' . $refer , 1, 1);
	else
		return true;
}

/**
 * 获取道具图片
 * 
 * @param mixed $goodId 
 * @access public
 * @return void
 */
function getImage($id, $type = 1, $sex = 1, $fileType = NULL)
{
	global $config;
	$imageUrl = '';
	if(!$fileType)
		$fileType = $type == 1 ? 'png' : 'jpg';

	// CDN序号 
	if ($type < 4)
		$cdnFlag = 1;
	else if ($type < 7)
		$cdnFlag = 2;
	else
		$cdnFlag = 3;

	//cdn可以后要修改
	$cdnFlag = '';
    $filePath = getAvatarImageDir($id, '', $fileType);
	switch($type)
	{
		case 1://avatar图,为png格式
			if(file_exists($config['avatarDir'] . $filePath)) $imageUrl = 'attachment/avatar/' . $filePath;
			else $imageUrl = $sex == 1 ? 'image/img/common/default_boy_avatar.png' : 'image/img/common/default_girl_avatar.png';
			break;
		case 2://用户头像,为jpg格式
			if($id == 100001) $imageUrl = 'image/img/common/zyj.jpg';
			elseif($id == 100002) $imageUrl = 'image/img/common/zyq.jpg';
			else
            {
				if(file_exists($config['pictureDir'] . $filePath)) $imageUrl = 'attachment/pic/' . $filePath;
                else $imageUrl = 'image/img/common/default_pic.jpg';
			}
			break;
		case 3://徽章图片,为jpg格式
			$filePath = getAvatarImageDir($id, '', 'gif');
			if(file_exists($config['badgeDir'] . $filePath)) $imageUrl = 'attachment/badge/' . $filePath;
			else $imageUrl = 'image/img/common/default_badge.jpg';
			break;
		case 4://道具图片，为jpg格式
			if(file_exists($config['shopGoodDir'] . $filePath)) $imageUrl = 'attachment/shop/good/' . $filePath;
			else $imageUrl = 'attachment/shop/default_good.jpg';
			break;
		case 5://商店图片，为jpg格式
			if(file_exists($config['shopIconDir'] . $filePath)) $imageUrl = 'attachment/shop/icon/' . $filePath;
			else $imageUrl = 'image/img/common/default_good.jpg';
			break;
		case 6://商店店主图片，为jpg格式
			if(file_exists($config['shopHostDir'] . $filePath)) $imageUrl = 'attachment/shop/host/' . $filePath;
			else $imageUrl = 'image/img/common/default_good.jpg';
			break;
		case 7://小游戏大图片
			if(file_exists($config['gameDir'] . '/big/' . $filePath)) $imageUrl = 'image/mg/big/' . $filePath;
			else $imageUrl = 'image/img/common/u7.jpg';
			break;
		case 8://小游戏小图片
			if(file_exists($config['gameDir'] . '/small/' . $filePath)) $imageUrl = 'image/mg/small/' . $filePath;
			else $imageUrl = 'image/img/common/u7.jpg';
			break;
		case 9://图书大图片
			$filePath = getAvatarImageDir($id);
			$filename = getImageName($id,'','');
			$filePath = $filePath . 'b_' . $filename . '.gif';
			if(file_exists($config['bookDir'] . $filePath)) $imageUrl = 'attachment/book/' . $filePath;
			else $imageUrl = 'image/img/common/default_book.jpg';
			break;
		case 10://图书小图片
			$filePath = getAvatarImageDir($id);
			$filename = getImageName($id,'','');
			$filePath = $filePath . 's_' . $filename . '.gif';
			if(file_exists($config['bookDir'] . $filePath)) $imageUrl = 'attachment/book/' . $filePath;
			else $imageUrl = 'image/img/common/default_book.jpg';
			break;
		default:
			break;
	}

    //$cdnUrl = preg_replace("/^([^.]+)(.*)$/", "\$1". $cdnFlag . "\$2", $config['cdnUrl']);
	if ($cdnUrl = $config['cdnUrl'])
	{
		$cdnUrl = explode('.', $cdnUrl);
		$cdnUrl[0] .= $cdnFlag;
		$cdnUrl = implode('.', $cdnUrl);
	}

	return $cdnUrl . $imageUrl;
}

/**
 * 发送邮件
 * 
 * @access public
 * @return bool
 */
function sendMail($email, $title, $body)
{
	global $config;

	require_once $config['libs'] . 'phpmailer/class.phpmailer.php';
	//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

	$mail             = new PHPMailer();

	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
											   // 1 = errors and messages
											   // 2 = messages only
  	//$mail->SMTPSecure    = "tls";
	$mail->SMTPAuth   = true;                  // enable SMTP authentication
	$mail->Host       = "58.68.236.120"; // sets the SMTP server
	$mail->Port       = 25;                    // set the SMTP port for the GMAIL server
	$mail->Username   = "service@ppl419.com"; // SMTP account username
	$mail->Password   = "service@2011";        // SMTP account password

	$mail->SetFrom('service@ppl419.com', 'ppl419');

	$mail->AddReplyTo("service@ppl419.com", "");

	$mail->Subject    = "=?UTF-8?B?" . base64_encode($title) . "?=";

	$mail->MsgHTML($body);

	$address = $email;
	$mail->AddAddress($address, "");

	//$mail->AddAttachment("images/phpmailer.gif");      // attachment
	//$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment

/*
	if(!$mail->Send()) {
		  echo "Mailer Error: " . $mail->ErrorInfo;
	} else {
		  echo "Message sent!";
	}
*/

	return $mail->Send();
}

/**
 * 生产随机字符串
 * 
 * @access public
 * @return string
 */
function genRandomString($length = 8) 
{
    $string = '';    
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';

    for ($p = 0; $p < $length; $p++) 
	{
        $string .= $characters[mt_rand(0, strlen($characters) - 1)];
    }

    return $string;
}

function setFeedBack($info)
{
	global $db, $config;

	require_once $config['libs'] . './DaChoose.php';
	require_once $config['libs'] . './dal/Dal.php';

	$dc = new DaChoose($db);
	$dal = new Dal();
	$dbObj = $dal->initDb($dc->setModule('common')->setAction('w')->getConfig());
	return $dbObj->query('INSERT INTO ppl_feedback(ub_id, ub_name, fd_apptype, fd_quetype, 
							fd_text, fd_timeline, fd_status, fd_appcate, fd_url, fd_apptypetwo, fp_dateline) 
	VALUES(' . $info['ubid'] . ', "' . $info['ubname'] . '", ' . $info['apptype'] . ', 
		' . $info['quetype'] . ', "' . $info['text'] . '", ' . time() . ', 1, "' . $info['appcate'] . '", 
		"' . $info['url'] . '", "' . $info['typetwo'] . '", ' . time() . ')');
}
//屏蔽html
function checkHtml($html) 
{
	$html = stripslashes($html);
	preg_match_all("/\<([^\<]+)\>/is", $html, $ms);

	$searchs[] = '<';
	$replaces[] = '&lt;';
	$searchs[] = '>';
	$replaces[] = '&gt;';
	
	if($ms[1]) 
	{
		$allowtags = 'img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote|object|param|embed';//允许的标签
		$ms[1] = array_unique($ms[1]);
		foreach ($ms[1] as $value) 
		{
			$searchs[] = "&lt;".$value."&gt;";
			$value = shtmlspecialchars($value);
			$value = str_replace(array('\\','/*'), array('.','/.'), $value);
			$value = preg_replace(array("/(javascript|script|eval|behaviour|expression)/i", "/(\s+|&quot;|')on/i"), array('.', ' .'), $value);
			if(!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) 
			{
				$value = '';
			}
			$replaces[] = empty($value)?'':"<".str_replace('&quot;', '"', $value).">";
		}
	}
	$html = str_replace($searchs, $replaces, $html);
	$html = addslashes($html);
	
	return $html;
}

/**
 * 将链接地址放入到cdn队列中等待更新 
 * 
 * @param mixed $cdnPicUrl 
 * @access public
 * @return void
 */
function refreshIntoCdn($cdnPicUrl)
{
	global $_SGLOBAL, $config, $cache;
	$cdnKey = 'refresh:cdn:key';

	require_once $config['libs'] . './dal/Dal.php';
	$dal = new Dal();
	$permCache = $dal->initCache($cache['permCache'], $cache['permCacheType']);
	return $permCache->rpush($cdnKey, $cdnPicUrl);
}

/**
 * 特殊avatar
 * 
 * @param mixed $uId 
 * @access public
 * @return void
 */
function getSpecialAvatar($uId)
{
	$avatarImg = '';
	if($uId == '100003')
		$avatarImg = 'image/special/sk.png';
	elseif($uId == '100004')
		$avatarImg = 'image/special/bt.png';
	elseif($uId == '100005')
		$avatarImg = 'image/special/pipilu.png';
	elseif($uId == '100006')
		$avatarImg = 'image/special/lxx.png';
	elseif($uId == '100007')
		$avatarImg = 'image/special/lk.png';
	elseif($uId == '100008')
		$avatarImg = 'image/special/yll.png';
	return $config['cdnUrl'] . $avatarImg;
}

/**
 * 设置登录记录进入队列 
 * 
 * @param mixed $uId 
 * @param mixed $uName 
 * @param mixed $uTName 
 * @access public
 * @return void
 */
function setLoginLog($uId, $uName, $uTName)
{
	global $_SGLOBAL, $config, $cache;
	$ip = getClientIp();
	require_once $config['libs'] . './dal/Dal.php';
	$dal = new Dal();
	$permCache = $dal->initCache($cache['permCache'], $cache['permCacheType']);
	//将用户id写入排行队列
	$permCache->rpush('user:login:log', 'INSERT INTO ppl_login_log SET ub_id = "' . $uId . '", ub_name = "' . $uName . '", ub_truename = "' . $uTName . '", login_ip = "' . $ip . '", login_dateline = "' . $_SERVER['REQUEST_TIME'] . '"');
	
}

/**
 *debug日记记录 
 * 
 * @param mixed $text 
 * @param int $mode debug模式，1-为直接屏幕显示 2-为文本日记
 * @param string $logFileName 如果是记录文本则这个可以指定记录文本日记的位置
 * @access public
 * @return void
 */
function debugLog($text, $mode = 2, $logFileName = './debugLog.log')
{
	$msg = 'Debug Time:' . date('Y-m-d H:i:s') . "\n" . 'Debug Message：' . $text . "\n";
	if($mode == 1)
	{
		echo $msg , '<br />';
		return $msg;
	}
	else
	{
		$fp = @fopen($logFileName, 'a+');
		if($fp)
		{
			fwrite($fp, $msg);
			fclose($fp);
			return $msg;
		}
		else
			return false;
	}
}

/**
 * 错误产生触发 
 * 
 * @access public
 * @return void
 */
function errorHandler($errNo, $errStr, $errFile, $errLine, $errContext)
{
	global $config;
	$str = '';
	$ignor = 0;
	$redirect = 1;
	$str = 'SiteURL:' . $config['pplUrl'] . "\n";
	switch ($errNo)
	{
		case E_USER_ERROR:
		case E_ERROR:
			$str .= "My ERROR[$errNo] $errStr\n";
			break;

		case E_USER_WARNING:
		case E_WARNING:
			$str .= "My WARING[$errNo] $errStr\n";
			break;  
	  
		case E_USER_NOTICE:
		case E_NOTICE:
			$str .= "My NOTICE [$errNo] $errStr\n";
			$redirect = 0;
			break;

		default:
			//$str .= "Unknown error type: [$errNo] $errStr\n";
			$ignor = 1;
			break;
	}

	if(!$ignor)
	{
		$str .= "Fatal error on line $errLine in file $errFile\n";

		if(!defined('ERROR_LOG_FILE'))
			define('ERROR_LOG_FILE', '/tmp/php_error.log');

		//记录文本日记
		$str = debugLog($str, 2, ERROR_LOG_FILE);

		//发送msn信息和邮件
		if(DEBUG_REPORT == 1)
		{
			isset($config['debugMsnList']) ? sendMsnMsg($str, $config['debugMsnList']) : '';
			isset($config['debugMailList']) ? sendMail($str, $config['debugMailList']) : '';
		}

		//异常跳转
		if(!defined('ERROR_REDIRECT_URL'))
			define('ERROR_REDIRECT_URL', $config['pplUrl'] . '50x.html');

		if($redirect)
			echo '<script>window.location.href="' . ERROR_REDIRECT_URL . '";</script>';
	}

	return true;
}

/**
 * send msn message
 *
 * @param string $msg
 * @param string $receive
 * @param string $sendMsn
 * @param string $sendPass
 */
function sendMsnMsg($msg = NULL, $receive = 'fengyue15@163.com', $sendMsn = 'pplzdy419@hotmail.com', $sendPass = '419419419')
{
	global $config;
	require_once $config['libs'] . './report/msn/msn.class.php';

	$msn = new MSN;
	if($msn->connect($sendMsn, $sendPass))
	{
		$msn->sendMessage($msn, (array)$receive);
		return true;
	}
	else
		return false;
}

/**
 * 随机抽取数字 
 * 
 * @param mixed $rSeed 
 * @access public
 * @return void
 */
function randomGold($rSeed)
{
	$res = $rSeed[0];
	$size = sizeof($rSeed);
	$start = rand(1, 100);
	$end = rand(1, 10);
	$randNum = $start*$end;
	if($randNum == 1000)
		$res = $rSeed[$size-1];
	else
	{
		$d = intval($randNum/100)+1;
		if($d <= 2)
			$res = $rSeed[$size-7];
		elseif($d <= 4)
			$res = $rSeed[$size-6];
		elseif($d <= 6)
			$res = $rSeed[$size-5];
		elseif($d <= 8)
			$res = $rSeed[$size-4];
		elseif($d <= 9)
			$res = $rSeed[$size-3];
		elseif($d <= 10)
			$res = $rSeed[$size-2];
	}
	return $res;
}

/**
 * 取得用户在线 
 * 
 * @param mixed $uIds 
 * @access public
 * @return void
 */
function getOnlineMem($uIds)
{
	global $_SGLOBAL, $config, $cache, $db;

	//创建登录的session到缓存中，并缓存用户信息
	require_once $config['libs'] . './dal/Dal.php';
	$dal = new Dal();
	require_once $config['libs'] . './DaChoose.php';
	$dc = new DaChoose($db);
	$dbObj = $dal->initDb($dc->setModule('common')->setAction('r')->getConfig());
	$dbObj->query('SELECT ub_id, ub_truename FROM ppl_online_users WHERE ub_id IN(' . $uIds . ') AND ou_lasttime > "' . ($_SGLOBAL['timestamp'] - $config['keepAlive']) . '"');
	return $dbObj->fetchAll();
}

/**
 * 取得用户的学校标志 
 * 
 * @param mixed $uId 
 * @access public
 * @return void
 */
function getMySchool($uId)
{
	global $_SGLOBAL, $config, $cache, $db;

	require_once $config['libs'] . './dal/Dal.php';
	$dal = new Dal();
	$tCache = $dal->initCache($cache['tempCache'], $cache['tempCacheType']);
	$cKey = 'main:school:flag:' . $uId;
	if(($res = $tCache->get($cKey)) === false)
	{
		require_once $config['libs'] . './DaChoose.php';
		$dc = new DaChoose($db);
		$dbObj = $dal->initDb($dc->setModule('school')->setAction('r')->getConfig());
		$dbObj->query('SELECT psch_id FROM ppl_xy_member WHERE ub_id = ' . $uId . ' LIMIT 1');
		if($rs = $dbObj->fetchRow())
		{
			$dbObj->query('SELECT psch_domain FROM ppl_xy_school WHERE psch_id = ' . $rs[0] . ' LIMIT 1');
			if($schDomain = $dbObj->fetchRow())
			{
				$tCache->set($cKey, $schDomain[0], 86400);
				return $schDomain[0];

			}
		}

		return false;
	}

	return $res;
}

/**
 * 链接地址转换为超链接
 *
 * @param string $message 查找内容
 * @access public
 * @return string 替换后的文本
 */
function changeUrl($message) {
    $message    = strtr($message,array('"' => '\"'));
    $mode       = '~(?<!href=)[\'"]?(ftp|http|https)://([0-9a-zA-Z?&=%./\-_#:]+)(?!</a>)~i';
	$replace    = '<a href="\\1://\\2" target="_blank">\\1://\\2</a>';
    
    return preg_replace($mode,$replace,$message);
}

/***/
function changeUrlOld($message)
{
    $search  = '/(ftp|http|https):\/\/([0-9a-zA-Z\?\&\=\%\.\/\-_#:]+)/iu';
    if(preg_match_all($search,$message,$result)){
        return $result;
    }
	$replace = '<a href="\\1://\\2" target="_blank">\\1://\\2</a>';
	return preg_replace($search, $replace, $message);
}

/**
 * 退出时删除在线信息 
 * 
 * @param mixed $uId 
 * @access public
 * @return void
 */

function delOnlineInfo($uId)
{
	global $db, $config, $cache;

	require_once $config['libs'] . './dal/Dal.php';
	require_once $config['libs'] . './DaChoose.php';

	$dc = new DaChoose($db);
	$dal = new Dal();

	$cObj = $dal->initCache($cache['tempCache'], $cache['tempCacheType']);
	$cObj->del('user:auth:' . $uId);

	$dbObj = $dal->initDb($dc->setModule('common')->setAction('w')->getConfig());
	$dbObj->query('DELETE FROM ppl_online_users WHERE ub_id = ' . $uId);

	return $dbObj->affectedRows() > 0;
}

/**
 * 从数组生成插入表的字段字符串
 *  
 * @param array $arrFeilds
 * @access public
 * @return string 结果串
 */
function makeFieldStringFromArray(array $arrFeilds = array())
{
    return '`'.implode('`,`',$arrFeilds).'`';        
}

/**
 * 从数组生成插入表的字段数据
 *
 * @param array $arrValues
 * @access public
 * @return string 结果串
*/
function makeValueStringFromArray(array $arrValues = array())
{
    return "'".implode("','",$arrValues)."'";
}

/**
 * 得到页数
 *
 * @param int $page
 * @access public
 * @return int 结果页码
 */
function getPageNumber($page)
{
    $page   = intval($page);
    if( 0 >= $page ) {
        return 0;
    }

    return $page - 1; 
}

/**
 * 检测当前页码是否有效
 *
 * @param int $nowPage 当前页码
 * @param int $perpage 每页显示的数量
 * @param int $totalRecords 总记录
 * @access public
 * @return int
 */
function verifyPageNumber($nowPage, $perpage, $totalRecords) {
    $totalPage  = ceil($totalRecords / $perpage);
    if($nowPage < 0 || $nowPage > $totalPage) {
        return 0;
    }

    return $nowPage;
}



/**
 * 检测记录ID的合法性
 *
 * 要是正确则返回正确值，错误返回-1
 * @param int $id
 * @access public
 * @return mix 是否合法 或 正确值
 */
function checkRecordId($id)
{
    if(isset($id) && preg_match('/^\d+$/',$id) > 0) {
       return $id; 
    }

    return false; 
}

/**
 * 去掉字符串两边的空格后，看元素是否还为真
 * 数字0也是为真
 *
 * @param String $element 
 * @access public
 * @return boolean 是否还为真
 */
function checkString($element = '')
{
    $element    = trim($element);
    if(is_numeric($element) || !empty($element)) {
        return true;
    }

    return false;
}

/**
 * 将数组里的下标跟下标对应的值连成一个字符串
 * 每个元素之前用给写的中间字符间隔
 *
 * @param array $arrData 处理数组数据
 * @param String $midString 中间字符
 * @access public
 * @return String 结果 
 */
function joinArrayKeyAndValue($arrData, $midString = '') 
{
    $resultString   = '';
    foreach($arrData as $key => $value) {
       $resultString    .= $key.$value.$midString; 
    }
    
    return $resultString; 
}

/**
 * 生成页模板里的$theUrl
 *
 * @param null
 * @return string
 */
function genTheUrl() {
    $theUrl     = "http://" . $_SERVER['HTTP_HOST'] . preg_replace('/&?p=\d+/', '', $_SERVER['REQUEST_URI']);
    if(preg_match("/\?/", $theUrl)) {
        return $theUrl;
    }
    
    return $theUrl . '?';
}

/**
 * 格式化HTML内容
 *
 * @param string $htmlContent
 * @access public
 * @return string
 */
function encodeHtml($htmlContent) {
    if(!get_magic_quotes_gpc()) {
        $htmlContent    = addslashes($htmlContent);
    }

    return htmlspecialchars($htmlContent);
}

/**
 * 是Ajax请求吗？
 *
 * @param null
 * @access public
 * @return boolean
 */
function isAjaxRequest() {
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])
        && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        return true;
    }
    
    return false;
}

/**
 * 获取侧边栏基本数据 
 * 
 * @param mixed $uid 
 * @param int $isspace  是否是基地
 * @access public
 * @return void
 */
function getSideBarInfo($uid)
{
	global $config,$_SGLOBAL;
	$sidebar = array();
	if(empty($uid)) return false;
	require_once $config['modules'] . './UserInfo.php';
	require_once $config['modules'] . './Badge.php';
    $uObj= new UserInfo;
    $badge  = new Badge();
	$userInfoArr = array('uId' => $uid);
	$uBase = $uObj->getUserBase($userInfoArr);
	$uHonor = $uObj->getUserHonor($userInfoArr);
    $uInfo = $uObj->getUserInfo($uBase['ub_id'],$uBase['ub_name']);
    $curBadges     = explode(':',$uHonor['uh_curbadge']);
    $curBadges     = array_filter($curBadges);
    $curBadges     = genUserCurBadges($curBadges, $uHonor['uh_badges'], 3);
    $curBadgesName = syncCurBadgesName($curBadges, $badge->getBadgeNameByIds($curBadges));
	include_once $config['modules'] . './Space.php';
	include_once $config['modules'].'./Fr.php';
	$space = new Space();
	$fr    = new Fr();
	//浏览次数
    $viewNum = $space->getSpaceViewNum($uid,'');

    if(!$_SGLOBAL['assign']['sidebar']['space']) {
        require_once $config['modules'] . './Blog.php';
        require_once $config['modules'] . './Tw.php';
        require_once $config['modules'] . './Group.php';
        require_once $config['modules'] . './Album.php';
        $blog       = new Blog();
        $totalBlog  = $blog->getTotalBlogByUid($uid);
        $tw         = new Tw();
        $totalTw    = $tw->getTotalTwByUid($uid);
        $album      = new Album(); 
        $totalAlbum = $album->getTotalAlbumByUid($uid);
        $group      = new Group();
        $totalGroup = $group->getTotalGroupByUid($uid);
    } else {
        $totalBlog  = 0;
        $totalTw    = 0;
        $totalAlbum = 0;
        $totalGroup = 0;
    } 

	//是否好友
	$isFriend = $_SGLOBAL['supeUid'] != $uid ? ($fr->isFriend($_SGLOBAL['supeUid'],$uid) ? true : false) : false;
    $sidebar       = array(
                        'uid' =>$uHonor['ub_id'],
                        'truename'=>$uBase['ub_truename'],
                        'avatar'=>$config['cdnUrl'] . str_replace($config['cdnUrl'], '' ,getImage($uHonor['ul_avatar'], 1, $uInfo['ui_sex'])),
                        'pic'=>getImage($uHonor['ub_id'], 2),
                        'zcredits'=>$uHonor['uh_zcredits'],
                        'golds'=>$uHonor['uh_golds'],
                        'level'=>$uObj->userLevel($uid),
                        'badgenum'=>$uHonor['uh_badgenum'],
                        'badge'=>$curBadges,
                        'badgeName' => $curBadgesName,
                        'star'=>getStar($uHonor['uh_credits']),
						'viewnum' => $viewNum,
                        'isFriend'=>$isFriend,
                        'totalBlog' => $totalBlog,
                        'totalTw' => $totalTw,
                        'totalAlbum' => $totalAlbum,
                        'totalGroup' => $totalGroup
                    );
    
    return $sidebar;
}

//同步数据库里查出来的徽章名跟当前徽章ID顺序一至
function syncCurBadgesName($curBadges, $curBadgesName) {
    $tempBadgesName     = array();
    foreach($curBadges as $key => $badgeId) {
        foreach($curBadgesName as $badge) {
            if($badge['badge_id'] == $badgeId) {
                $tempBadgesName[$key]   = $badge['badge_name'];
                break;
            }
        } 
    }
    return $tempBadgesName;
}

//生成用户当前的佩戴徽章
function genUserCurBadges($curBadges, $userBadges, $limitNumber = 3) {
    $totalCurBadges= count($curBadges);
    if($limitNumber > $totalCurBadges) {
        $userBadges     = explode('|', $userBadges);
        foreach($userBadges as $key => $badge) {
            $arrBadgeInfo   = explode(':', $badge);
            if(empty($arrBadgeInfo[1]) || in_array($arrBadgeInfo[1], $curBadges)) {
                continue;
            }
            $totalCurBadges ++;
            $curBadges[]    = $arrBadgeInfo[1];
            if($totalCurBadges >= $limitNumber) {
                break;
            }
        }
    }

    return $curBadges;
}

/**
 * getMainnavInfo 
 * 
 * @param mixed $uid 
 * @param int $limit 
 * @access public
 * @return void
 */
function getMainnavInfo($uid, $limit = 4)
{
	global $config,$_SGLOBLE;
	$mainnav= array();
	if(empty($uid)) return false;
	require_once $config['modules'] . './Group.php';
	$group = new Group();
	$groups = $group->getUserGroup($uid, $limit);
	if(!empty($groups))
	{
		foreach($groups as $k=>$v)
		{
			if($v['group_id']) $groupIds[] = $v['group_id'];
		}
	}
	if($groupIds)
	{
		$idStr = implode(',',$groupIds);
		$groupInfo = $group->getGroupList($idStr,false,'group_id');
		foreach($groups as $k=>$v)
		{
			$groupInfo[$v['group_id']]['level'] = $v['gu_grade'];
			if(!empty($groupInfo[$v['group_id']])) $list[] = $groupInfo[$v['group_id']];
		}
	}
	$mainnav = array(
			'groupInfo'=>$list,
	
	);
	return $mainnav;
}

/**
 * 验证字符串的合法长度，集成是否过滤回车字符
 * 使用示例：
 * (1) $message     = verifyStringLen($content);
 * (2) $message     = verifyStringLen($content, $maxLen, true, true);
 * (3) $message     = verifyStringLen($content, array($minLen, $maxLen), true, true);
 * (4) 其它
 *
 * @param string $content 待测的字符串
 * @param int or array 长度规则信息
 * @param boolean $filterEnter 是否过滤回车标识，默认为true
 * @param boolean $filterMoreSpace 是否过滤多个空格，默认为true
 *
 * @return boolean or string
 */
function verifyStringLen($content, $lenInfo = 158, $filterEnter = true, $filterMoreSpace = true) {
    $errorMsg       = '字数有误！允许的字符长度：';
    $content         = trim($content);                //去掉两端的空格
    if(is_array($lenInfo)) {
        $minLen     = $lenInfo[0];
        $maxLen     = $lenInfo[1];
    } else {
        $minLen     = 1;
        $maxLen     = $lenInfo;
    }

    if($filterEnter === true) {
        $content    = filterEnter($content);
    }
    $realLen        = mb_strlen($content, 'utf-8');

    if($realLen < $minLen || $realLen > $maxLen) {
        if($minLen != 0) {
            return array($errorMsg . $minLen . '~' . $maxLen . '。');
        }
        return array($errorMsg . '不超过' . $maxLen . '。');
    }
    
    if(true == $filterMoreSpace) {
        $content         = preg_replace('/\s+/m', ' ', $content);  //去掉连续的空格
    }

    return $content;
}

/**
 * 删除所有的换行
 *
 * @param string $content
 * @access public
 * @return string 
 */
function filterEnter($content) {
    return strtr($content, array("\n" => '', "\r" => ''));
}

//得到星座名
function getAstro($month, $day){
    $s      = '魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯';
    $arr    = array(20,19,21,21,21,22,23,23,23,23,22,22);

    return mb_substr($s, $month*2-($day<$arr{$month-1}?2:0), 2, 'utf-8') . '座';
}
